package com.net.library.net;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.*;

import java.io.IOException;

/**
 * Created by 吴昶 on 2018/9/13.
 */
public class FileRequstBody<T> extends RequestBody {

    private RequestBody requestBody;

    private FileCallBack<T> callBack;

    private BufferedSink bufferedSink;

    public FileRequstBody(RequestBody requestBody,FileCallBack<T> callBack){
        this.requestBody=requestBody;
        this.callBack=callBack;
    }

    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (sink instanceof Buffer) {
                requestBody.writeTo(sink);
            return;
        }
            if(bufferedSink==null){
                bufferedSink= Okio.buffer(getSink(sink));
            }
            requestBody.writeTo(bufferedSink);
            bufferedSink.flush();
    }

    private Sink getSink(Sink sink){
        return new ForwardingSink(sink) {
            private long total=0;
            private long progress=0;
            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if(total==0) {
                    total = requestBody.contentLength();
                }
                progress+=byteCount;
                Observable.just(progress).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) throws Exception {
                                callBack.onLoading(total,progress);
                            }
                        });
            }
        };
    }

}
